package com.ygo.feihua;
import android.content.*;
import android.graphics.*;
import android.net.*;
import android.os.*;
import android.support.v7.app.*;
import android.support.v7.widget.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import cn.bmob.v3.*;
import cn.bmob.v3.datatype.*;
import cn.bmob.v3.exception.*;
import cn.bmob.v3.listener.*;
import com.yalantis.ucrop.*;
import com.ygo.feihua.BmobTable.*;
import java.io.*;
import java.util.*;

import android.support.v7.widget.Toolbar;
import com.ygo.feihua.Management.*;
import com.ygo.feihua.util.*;
import com.yuyh.library.imgsel.*;
import com.yuyh.library.imgsel.ui.*;

public class YonghuZiliao extends AppCompatActivity
{

	TextView zl_sj,zl_ql,zl_sq,zl_name,zl_qm;
	Button zl_td;
	UserManagement um;
	ImageView zl_touxiang;
	Gongju gj;
	private DialogUtils du;
	boolean jing=false;

	private static final int PHOTO_REQUEST_GALLERY = 1;
    private static final int PHOTO_REQUEST_CUT = 2;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO: Implement this method
		super.onCreate(savedInstanceState);
		setContentView(R.layout.yonghu_ziliao);
		
		um=UserManagement.getDx();
		gj = Gongju.getdx(this);
		du=DialogUtils.getdx(this);
		
		du.dialogj1(false, "", "加载中,请稍等");
		zl_sj = (TextView) findViewById(R.id.zl_sj);
		zl_ql = (TextView) findViewById(R.id.zl_ql);
		zl_sq = (TextView) findViewById(R.id.zl_sq);
		zl_td = (Button) findViewById(R.id.zl_td);
		zl_name = (TextView) findViewById(R.id.zl_name);
		zl_qm = (TextView) findViewById(R.id.zl_qm);
		zl_touxiang = (ImageView) findViewById(R.id.zl_touxiang);
		Toolbar toolbar=(Toolbar) findViewById(R.id.toolbar);
		gj.cshToolbar(toolbar,"用户资料");
		toolbar.setNavigationOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					Intent intent=new Intent();
					intent.putExtra("isd", "sx");
					setResult(0, intent);
					finish();
					// TODO: Implement this method
				}
			});
		
		zl_touxiang.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					
					if (jing){			
						ISNav.getInstance().toListActivity(YonghuZiliao.this, Gongju.getPicConfig(1), 233);
						
					}else{
						gj.show("请等待信息加载完毕后操作");
					}
				
					// TODO: Implement this method
				}
			});



		zl_qm.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(final View view)
				{
					if (jing)
					{
						View[] v=du.dialoge(false, "", "请输入签名");
						Button qd=(Button) v[1];
						final EditText ed=(EditText) v[0];
						ed.setSingleLine(true);
						ed.setText(zl_qm.getText().toString().trim());
						qd.setOnClickListener(new OnClickListener(){

								@Override
								public void onClick(View p1)
								{
									String s=ed.getText().toString().trim();
									if (s.length() > 50){
										gj.show("签名不能超过50字");
									}else{
										if (s.equals(""))
										{
											gj.show("签名不能为空");
										}
										else
										{

											um.getUser().setsignature(s);
											um.getUser().update(um.getUser().getObjectId(), new UpdateListener(){

													@Override
													public void done(BmobException p1)
													{
														if (p1 == null)
														{
															um.sxUser();
															gj.show("修改成功");
															du.dis();
															zl_qm.setText(um.getUser().getsignature());

														}
														else
														{
															gj.toastBmobException(view,"添加失败",p1);
															
															//gj.show("修改失败" + p1.getMessage());
															du.dis();
														}
														// TODO: Implement this method
													}
												});
										}
										// TODO: Implement this method
									}
								}
							});
					}
					else
					{
						gj.show("请等待信息加载完毕后操作");
					}

					// TODO: Implement this method
				}
			});


		BmobQuery<MyUser> bq=new BmobQuery<MyUser>();
		bq.getObject(um.getUser().getObjectId(), new QueryListener<MyUser>() {

				@Override
				public void done(MyUser p1, BmobException p2)
				{
					if (p2 == null)
					{	
						gj.setTouxiang(zl_touxiang, p1);
						zl_name.setText(p1.getUsername());
						if (p1.getsignature() != null)
						{
							zl_qm.setText(p1.getsignature());
						}
						else
						{
							zl_qm.setText("点击输入签名");
						}
						zl_sj.setText(p1.getCreatedAt());
						int sq=p1.getShequ_qx();
						switch (sq)
						{
							case 0:
								zl_sq.setText("良好");
								break;
							case 1:
								zl_sq.setText("禁言中");
						}

						int ql=p1.getLiaotian_qx();
						switch (ql)
						{
							case 0:
								zl_ql.setText("良好");
								break;
							case 1:
								zl_ql.setText("禁言中");
						}
						jing = true;
					}
					else
					{
						if (um.getUser() != null)
						{
							gj.setTouxiang(zl_touxiang, um.getUser());
							zl_name.setText(um.getUser().getUsername());
							if (um.getUser().getsignature() != null)
							{
								zl_qm.setText(um.getUser().getsignature());
							}
							else
							{
								zl_qm.setText("点击输入签名");
							}
							zl_sj.setText(um.getUser().getCreatedAt());
							int sq=um.getUser().getShequ_qx();
							switch (sq)
							{
								case 0:
									zl_sq.setText("良好");
									break;
								case 1:
									zl_sq.setText("禁言中");
							}

							int ql=um.getUser().getLiaotian_qx();
							switch (ql)
							{
								case 0:
									zl_ql.setText("良好");
									break;
								case 1:
									zl_ql.setText("禁言中");
							}
							jing = true;
						}
						gj.toastBmobException(zl_td, "加载失败", p2);
						
					}
					du.dis();

					// TODO: Implement this method
				}

			});
			
		zl_td.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					um.logOutUser();
					gj.show("退出登录成功");
					Intent intent=new Intent();
					intent.putExtra("isd", "d");
					setResult(0, intent);
					finish();
					// TODO: Implement this method
				}
			});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		// TODO: Implement this method
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			Intent intent=new Intent();
			intent.putExtra("isd", "sx");
			setResult(0, intent);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		// TODO: Implement this method
		super.onActivityResult(requestCode, resultCode, data);	
		
		if (resultCode == RESULT_OK && requestCode == 233) {
			if (data != null) {
				ArrayList<String> photos = data.getStringArrayListExtra(ISListActivity.INTENT_RESULT);			
				String pa=photos.get(0);
				startCropActivity(Uri.fromFile(new File(pa)),"tx_"+um.getUser().getUsername()+".png");		
					}
				}
		
		switch (requestCode){
			case 234:
				if (resultCode == RESULT_OK) {
				
					final Uri selectedUri = data.getData();
					if (selectedUri != null) {
						startCropActivity(data.getData(),"tx_"+um.getUser().getUsername()+".png");
					
					}
				}
				break;
			case UCrop.REQUEST_CROP:
			if(data!=null){
					 du.dialogj1(false, "", "正在替换中,请稍等");
				final BmobFile bmobFile = new BmobFile(new File(gj.PATH_GEN + "ygo助手/image/touxiang/"+"tx_"+um.getUser().getUsername()+".png"));
				 bmobFile.uploadblock(new UploadFileListener() {

					 @Override
					 public void done(BmobException p1)
					 {
					 if (p1 == null){
					 MyUser myu1=new MyUser();
					 myu1.setavatar(bmobFile);
					 myu1.update(um.getUser().getObjectId(), new UpdateListener() {

					 @Override
					 public void done(BmobException p1){
					 if (p1 == null){
							
					 um.sxUser();
					 gj.setTouxiang(zl_touxiang, um.getUser());
					 gj.show("替换成功");
					 du.dis();				 
					 }else{
						 gj.toastBmobException(zl_touxiang,"替换失败",p1);
						 
					 gj.show("替换失败" + p1.getMessage());
					 du.dis();
					 }
					 // TODO: Implement this method
					 }


					 });
					 }else{
						 gj.toastBmobException(zl_touxiang,"上传失败",p1);
						 
					 //gj.show("上传失败" + p1.getMessage());
					 du.dis();

					 }
					 // TODO: Implement this method
					 }



					 @Override
					 public void onProgress(Integer value)
					 {
					 // 返回的上传进度（百分比）
					 //  gj.show(value+"");

					 }
					 });

					 }
				break;
			case PHOTO_REQUEST_GALLERY: 
				if (data != null){                 
					startPhotoZoom(data.getData(), 1024);
				}

				break;
			case PHOTO_REQUEST_CUT:
				if (data != null) 
					setPicToView(data);
				break; 


		}

	}
	private void startCropActivity(Uri uri,String FileName) {
		UCrop ucrop = UCrop.of(uri, Uri.fromFile(new File(gj.PATH_GEN + "ygo助手/image/touxiang/", FileName)));
		
		ucrop = ucrop.withAspectRatio(1,1);
		
		//ucrop.withAspectRatio(16, 9) .withMaxResultSize(144, 144);
		UCrop.Options options = new UCrop.Options();
		//设置裁剪图片的保存格式 
		options.setCompressionFormat(Bitmap.CompressFormat.PNG); 
		//设置裁剪图片的图片质量
		options.setCompressionQuality(100);
		//设置你想要指定的可操作的手势
		//options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL); 
		//设置uCropActivity里的UI样式 
		/*options.setMaxScaleMultiplier(5);
		 options.setImageToCropBoundsAnimDuration(666); 
		 options.setDimmedLayerColor(Color.CYAN);
		 options.setOvalDimmedLayer(true);
		 options.setShowCropFrame(false); 
		 options.setCropGridStrokeWidth(10); 
		 options.setCropGridColor(Color.GREEN);
		 options.setCropGridColumnCount(2);
		 options.setCropGridRowCount(1);
		 ucrop.withOptions(options);*/
		ucrop.start(this);		
   }
	
    private void startPhotoZoom(Uri uri, int size)
    {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // crop为true是设置在开启的intent中设置显示的view可以剪裁
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1); 
        intent.putExtra("aspectY", 1);
        // outputX,outputY 是剪裁图片的宽高
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("return-data", true); 
		// intent.putExtra("output", Uri.fromFile(new File(Environment.getExternalStorageDirectory().toString() + "/ygo助手/image/"))); 
		//  intent.putExtra("outputFormat", "png");//返回格式 
        intent.putExtra("scale", true);//支持缩放

        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    } 


    // 保存到sdcard
    public  String savePic(Bitmap b)
	{

        FileOutputStream fos = null;
        try
		{
            File f = new File(gj.PATH_GEN + "ygo助手/image/touxiang/" , "tx_"+um.getUser().getUsername()+".png");
            if (f.exists())
			{
                f.delete();
            }

            fos = new FileOutputStream(f);
            if (null != fos)
			{
                b.compress(Bitmap.CompressFormat.PNG, 100, fos);

                fos.flush();
                fos.close();
                return gj.PATH_GEN + "ygo助手/image/touxiang/"+"tx_"+um.getUser().getUsername()+".png";
            }
        }
		catch (FileNotFoundException e)
		{
            e.printStackTrace();
        }
		catch (IOException e)
		{
            e.printStackTrace();
        }
        return null;
    }



	//将进行剪裁后的图片显示到UI界面上 
	private void setPicToView(Intent picdata)
	{

		Bundle bundle = picdata.getExtras();
		if (bundle != null)
		{
			du.dialogj1(false, "", "正在替换中,请稍等");
			Bitmap photo = bundle.getParcelable("data");

			String pp1=  savePic(photo);

			final BmobFile bmobFile = new BmobFile(new File(pp1));
			bmobFile.uploadblock(new UploadFileListener() {

					@Override
					public void done(BmobException p1)
					{
						if (p1 == null)
						{
							MyUser myu1=new MyUser();
							myu1.setavatar(bmobFile);
							myu1.update(um.getUser().getObjectId(), new UpdateListener() {

									@Override
									public void done(BmobException p1)
									{
										if (p1 == null)
										{
											um.sxUser();
											//   Glide.with(getActivity()).load(Uri.parse(bmobFile.getFileUrl(getActivity()))).dontAnimate().placeholder(R.drawable.sc_tb).into(wo_tx);             
											gj.setTouxiang(zl_touxiang, um.getUser());

											gj.show("替换成功");
											du.dis();
										}else{
											gj.toastBmobException(zl_touxiang,"替换失败",p1);
											
											//gj.show("替换失败" + p1.getMessage());
											du.dis();
										}
										// TODO: Implement this method
									}


								});
						}else{
							gj.toastBmobException(zl_touxiang,"上传失败",p1);
							
							//gj.show("上传失败" + p1.getMessage());
							du.dis();
						}
						// TODO: Implement this method
					}



					@Override
					public void onProgress(Integer value)
					{
						// 返回的上传进度（百分比）
					}
				});

		}
	}


}
